//
//  HYFTabBarItem.m
//  MyOCWeibo
//
//  Created by 黄勇锋 on 16/10/8.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

#import "HYFTabBarItem.h"
#import <objc/runtime.h>

@implementation HYFTabBarItem

- (void)setBadgeValue:(NSString *)badgeValue{
    
    [super setBadgeValue:badgeValue];
    
    //如果 badgeValue 为 nil,那么直接返回
    if (badgeValue == nil) {
        return;
    }
    
    //利用KVC 取到 tabBarItem 对应的控制器
    UITabBarController * target = [self valueForKeyPath:@"_target"];
    
    for (UIView *tabBarChild in target.tabBar.subviews) {
        //找UITabBarButton
        if ([tabBarChild isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            for (UIView *tabBarButtonChild in tabBarChild.subviews) {
                
                if ([tabBarButtonChild isKindOfClass:NSClassFromString(@"_UIBadgeView")]) {
                    
                    for (UIView *badgeViewChild in tabBarButtonChild.subviews) {
                        
                        if ([badgeViewChild isKindOfClass:NSClassFromString(@"_UIBadgeBackground")]) {
                            
                            unsigned int count;
                            
                            Ivar *vars = class_copyIvarList(NSClassFromString(@"_UIBadgeBackground"), &count);
                            
                            for (int i = 0; i< count; i++) {
                                
                                Ivar var = vars[i];
                                //获取var 的名字
                                NSString *name = [NSString stringWithCString:ivar_getName(var) encoding:NSUTF8StringEncoding];
                                
                                NSString *type = [NSString stringWithCString:ivar_getTypeEncoding(var) encoding:NSUTF8StringEncoding];
                                
                                //判断一下是否是 _image 类型,然后通过 KVC 赋值
                                if ([name isEqualToString:@"_image"]) {
                                    
                                    [badgeViewChild setValue:[UIImage imageNamed:@"main_badge"] forKeyPath:name];
                                }
                            }
                            free(vars);
                        }
                    }
                }
            }
        }
    }
}



@end
